The Array class in C#

System.Array is an important class to know and understand as almost any programming work has arrays.

Array is an abstract class, so you cannot establish and instance of it. That is OK because it is really just a “function holder” class.  The term “function holder” is not an official C# term, but it is a name I give classes that really just exist to hold functions.  Array is a “function holder” for array functions.

Lets take a moment to learn a few of the functions in the Array class. We are going to use an array of high scores to learn from.

Array.Sort

Let start by creating an array of high scores. The following code has a function that takes a score and adds it to the list if it is greater than the lowest high score and sorting them.

using System;

namespace ArrayLearning
{
    class Program
    {
        static int[] highScores = new int[12];

        static void Main(string[] args)
        {
            // keep that top 12 high scores
            AddScore(10100);
            AddScore(13710);
            AddScore(14190);
            AddScore(12130);
            AddScore(12130);
            AddScore(16140);
            AddScore(19320);
            AddScore(07250);
            AddScore(18140);
            AddScore(08090);
            AddScore(10010);
            AddScore(14380);
            AddScore(18140);
            AddScore(12190);
            AddScore(19320);
        }

        static void AddScore(int newScore)
        {
            // Pre-sort the high scores in case somehow the
            // first one is not the lowest.
            Array.Sort(highScores);

            // If the new score is greater than the lowest
            // high score, replace the lowest high score
            if (highScores[0] < newScore)
                highScores[0] = newScore;

            // Now resort the scores as the new score may
            // not be in the right place
            Array.Sort(highScores);

            DisplayHighScores();
        }

        private static void DisplayHighScores()
        {
            // Print the new high scores
            for (int i = highScores.Length - 1; i > -1; i--)
            {
                Console.WriteLine(highScores[i]);
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            Console.WriteLine();
        }
    }
}

Ok, I am not saying this is the proper way to handle high scores in a game.  I am just demonstrating Array.Sort for you.

Array.Clear

Ok, lets show an example of Array.Clear. This is a very simple function that sets all the values in the array to their default value. Booleans have a default value of false. Double, Int32, Int64, etc, have a default value of 0. Reference types have a default value of null.

Here is an enhancement to the above snippet that allows demonstrates clearing an entire array. Notice Array.Clear takes the array, then the starting item in the array and the number items in the array. In this example we clear the entire array, but that is not required.

using System;

namespace ArrayLearning
{
    class Program
    {
        static int[] highScores = new int[12];

        static void Main(string[] args)
        {
            // keep that top 12 high scores
            AddScore(10100);
            AddScore(13710);
            AddScore(14190);
            AddScore(12130);
            AddScore(12130);
            AddScore(16140);
            AddScore(19320);
            AddScore(07250);
            AddScore(18140);
            AddScore(08090);
            AddScore(10010);
            AddScore(14380);
            AddScore(18140);
            AddScore(12190);
            AddScore(19320);

            // Clear the high scores
            ClearHighScores();
        }

        static void AddScore(int newScore)
        {
            // Pre-sort the high scores in case somehow the
            // first one is not the lowest.
            Array.Sort(highScores);

            // If the new score is greater than the lowest
            // high score, replace the lowest high score
            if (highScores[0] < newScore)
                highScores[0] = newScore;

            // Now resort the scores as the new score may
            // not be in the right place
            Array.Sort(highScores);

            DisplayHighScores();
        }

        public static void ClearHighScores()
        {
            Console.WriteLine("Clearing High Scores!");
            Array.Clear(highScores, 0, highScores.Length);
            DisplayHighScores();
        }

        private static void DisplayHighScores()
        {
            // Print the new high scores
            for (int i = highScores.Length - 1; i > -1; i--)
            {
                Console.WriteLine(highScores[i]);
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            Console.WriteLine();
        }
    }
}

Array.IndexOf

Maybe you want to display the place in the top 12 that the player scored. However, the way we are adding the score does not track the new score’s place. So we need to find the place. Here is a small enhancement to the above code that demonstrates the use of Array.IndexOf to find the place.

Notice the addition of the DisplayCurrentPlace function and it’s use of Array.IndexOf. Also since the array is actually sorted with the lowest number at index 0 and the highest score at index 11, I can just subtract the index from the max lengh of 12 high scores to get the correct place.

using System;

namespace ArrayLearning
{

    class Program
    {
        public static int MAX = 12;
        static int[] highScores = new int[MAX];

        static void Main(string[] args)
        {
            // keep that top 12 high scores
            AddScore(10100);
            AddScore(13710);
            AddScore(14190);
            AddScore(12130);
            AddScore(12130);
            AddScore(16140);
            AddScore(19320);
            AddScore(07250);
            AddScore(18140);
            AddScore(08090);
            AddScore(10010);
            AddScore(14380);
            AddScore(18140);
            AddScore(12190);
            AddScore(19320);
            AddScore(06320);

            // Clear the high scores
            ClearHighScores();
        }

        static void AddScore(int newScore)
        {
            // Pre-sort the high scores in case somehow the
            // first one is not the lowest.
            Array.Sort(highScores);

            // If the new score is greater than the lowest
            // high score, replace the lowest high score
            if (highScores[0] < newScore)
            {
                highScores[0] = newScore;

                // Now resort the scores as the new score may
                // not be in the right place
                Array.Sort(highScores);

                DisplayHighScores();
                DisplayCurrentPlace(newScore);
            }
        }

        public static void ClearHighScores()
        {
            Console.WriteLine("Clearing High Scores!");
            Array.Clear(highScores, 0, highScores.Length);
            DisplayHighScores();
        }

        private static void DisplayHighScores()
        {
            // Print the new high scores
            for (int i = highScores.Length - 1; i > -1; i--)
            {
                Console.WriteLine(highScores[i]);
            }
        }

        private static void DisplayCurrentPlace(int newScore)
        {
            Console.WriteLine(String.Format("You placed number {0} out the top 12.", MAX - Array.IndexOf(highScores, newScore)));

            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            Console.WriteLine();
        }
    }
}

Well, these were three simple examples of using the Array class. As you can see it is little more than a “function holder”.

If you have an example of a function in the Array class, please post it here in the comments.

Leave a Reply

How to post code in comments?